

from xml.sax import ContentHandler

class RSSHandler (ContentHandler):
  def __init__(self,tag,flds):
      ContentHandler.__init__(self)
      self.__flds = flds
      self.__item = None
      self.__type = None
      self.__newobj = None
      self.__objs = []
      self.__item_tag = tag
      

  def characters(self,data):
      if self.__item:
          self.__newobj[self.__item] = self.__newobj[self.__item] + data
      
  def startElement(self, tag, attrs):
      if tag == self.__item_tag:
          self.__newobj = {}
      elif self.__newobj is not None and tag in self.__flds.keys():
          self.__item,self.__type  = self.__flds[tag]
          self.__newobj[self.__item] = ""
      else:
        self.__item = None
        self.__type = None
        
  def endElement(self, tag):
      if self.__item:
        self.__newobj[self.__item] = self.__type( self.__newobj[self.__item])
      if tag == self.__item_tag:
        self.__objs.append(type('Item', (object,), self.__newobj))

      self.__item = None
      

  def getItems(self):
    return self.__objs



class RssReader:
  def __init__(self,url):
    self.url = url
    self.desc = {}
    self.tag = None


  def add_item_desc(self, **desc):
    self.desc[desc["remote_name"]] = (desc["local_name"] ,desc["type"])
    return self

  def set_item_tag(self,tag):
    self.tag = tag

  def read(self):
    from urllib2 import urlopen
    from xml.sax import make_parser

    parser = make_parser()
    rss = RSSHandler(self.tag , self.desc)
    parser.setContentHandler(rss)
    parser.parse(urlopen(self.url))
    return rss.getItems()


